<template>
  <div class="app-container">
    <div style="width: 100%;margin-bottom:10px;justify-content: flex-end" class="flex-row">
      <el-button type="primary" @click="addItem('',false)">新增数据表</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
        type="index"
        label="序号"
        :index="indexMethod"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="tableCode"
        label="数据表名"
        align="center">
      </el-table-column>
      <el-table-column
        prop="correlationType"
        label="关联类型"
        align="center">
      </el-table-column>
      <el-table-column
        prop="mainTable"
        label="主表"
        align="center">
      </el-table-column>
      <el-table-column
        prop="mainTableField"
        label="主表关联字段"
        align="center">
      </el-table-column>
      <el-table-column
        prop="slaveTable"
        label="从表"
        align="center">
      </el-table-column>
      <el-table-column
        prop="slaveTableField"
        label="从表关联字段"
        align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        width="250"
        align="center"
      prop="handle">
        <template slot-scope="scope">
          <el-button type="text" @click="addItem(scope.row,false)">编辑</el-button>
          <el-button type="text" @click="delItem(scope.row)"
          :disabled="tableData.length != 1 && scope.$index == 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="width: 100%;margin-top:10px;justify-content: flex-end" class="flex-row">
      <el-pagination
        background
        layout="sizes,prev,pager,next,jumper,total"
        :page-size="paging.pageSize"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="paging.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog-comp :appendToBody="true" :title="dialogTitle" width="30%" ref="refDialogForm"
    :hasFooter="true" @throwDialogEmit="saveSubmit">
      <el-form label-position="right" label-width="120px" :model="formType" :rules="formRules"
      v-loading="formLoading" :element-loading-text="loadingText" ref="refForm">
        <el-form-item label="数据类型" style="width: 100%" prop="correlationType">
          <el-select placeholder="请选择数据类型" clearable style="width: 100%"
          v-model="formType.correlationType">
            <el-option label="数据主表" value="数据主表" v-if="!tableData.length"></el-option>
            <el-option label="数据从表" value="数据从表" v-if="tableData.length"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联主表" style="width: 100%" v-if="formType.correlationType == '数据主表'
        || formType.correlationType == '数据从表'"
        prop="mainTable">
          <el-select placeholder="请选择关联主表" clearable style="width: 100%" v-model="formType.mainTable"
          filterable @change="changeMainTable" :disabled="formType.correlationType == '数据从表'">
            <el-option v-for="item in querySurfaceData" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主表关联字段" style="width: 100%" v-if="formType.correlationType == '数据主表'
|| formType.correlationType == '数据从表'"
        prop="mainTableField">
          <el-select placeholder="请选择主表关联字段" clearable style="width: 100%"
          v-model="formType.mainTableField" filterable>
            <el-option v-for="item in surfaceList" :key="item.columnName" :label="item.columnName" :value="item.columnName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联从表" style="width: 100%" v-if="formType.correlationType == '数据从表'"
        prop="slaveTable">
          <el-select placeholder="请选择关联从表" clearable style="width: 100%"
          v-model="formType.slaveTable" filterable @change="changeSlaveTable">
            <el-option v-for="item in querySurfaceData" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="从表关联字段" style="width: 100%" v-if="formType.correlationType == '数据从表'">
          <el-select placeholder="请选择从表关联字段" clearable style="width: 100%"
          v-model="formType.slaveTableField" filterable>
            <el-option v-for="item in surfaceSlaveList" :key="item.columnName" :label="item.columnName" :value="item.columnName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog-comp>
  </div>
</template>

<script>
import {addSurface, delSurface, editSurface, getSurfaceList, inquireData, querySurfaceList} from '@/api/public/index'
export default {
  name: "JointTableSetting",
  props:{
    tableName:{
      type:String,
      default:''
    },
    tableId:{
      type:String,
      default:''
    }
  },
  data(){
    var validateMainTable = (rule, value, callback) => {
      if (this.formType.correlationType == '数据主表' && !value) {
        return callback(new Error('请选择关联主表'));
      }
      else{
        return callback()
      }
    };
    var validateMainTableField = (rule, value, callback) => {
      if (this.formType.correlationType == '数据主表' && !value) {
        return callback(new Error('请选择主表关联字段'));
      }
      else{
        return callback()
      }
    };
    var validateSlaveTable = (rule, value, callback) => {
      if (this.formType.correlationType == '数据从表' && !value) {
        return callback(new Error('请选择关联从表'));
      }
      else{
        return callback()
      }
    };
    var validateSlaveTableField = (rule, value, callback) => {
      if (this.formType.correlationType == '数据从表' && !value) {
        return callback(new Error('请选择从表关联字段'));
      }
      else{
        return callback()
      }
    };
    return {
      loadingText:'数据表加载中...',
      tableData:[],
      paging:{
        currentPage:1,
        pageSize:10,
        total:0
      },
      showInput:false,
      formLoading:false,
      disableVal:false,
      formType:{
        id:'',
        correlationType:'',//关联类型
        mainTable:'',//关联主表
        mainTableField:'',//主表关联字段
        slaveTable:'',//从表
        slaveTableField:'',//从表关联字段
      },
      formRules:{
        correlationType:[{required:true,message:'请选择数据类型',trigger:'change'}],
        mainTable:[{ validator: validateMainTable, trigger: 'change' }],
        mainTableField:[{ validator: validateMainTableField, trigger: 'change' }],
        slaveTable:[{ validator: validateSlaveTable, trigger: 'change' }],
        slaveTableField:[{ validator: validateSlaveTableField, trigger: 'change' }],
      },
      dialogTitle:'新增数据表',
      querySurfaceData:[],
      surfaceList:[],
      surfaceSlaveList:[]
    }
  },
  created() {
    querySurfaceList().then(res => {
      if(res.code == 200){
        this.querySurfaceData = res.data
      }
      else{
        this.querySurfaceData = []
      }
    })

    this.getTableList()
  },
  methods:{
    indexMethod(index){
      return (this.paging.currentPage - 1) * this.paging.pageSize + index + 1
    },
    addItem(item,bol){
      this.$refs.refDialogForm.throwOpenDialog()
      if(item && bol){
        this.dialogTitle = '查看数据表'
        console.log(item,'item')
        this.changeMainTable(item.mainTable)
        Object.assign(this.formType,{
          ...item
        })
      }
      else if(item){
        this.dialogTitle = '编辑数据表'
        this.changeMainTable(item.mainTable)
        Object.assign(this.formType,{
          ...item
        })
      }
      else{
        this.dialogTitle = '新增数据表'
        const keys = Object.keys(this.formType)
        for(let val of keys){
          this.formType[val] = ''
        }
        if(this.tableData.length >= 1){
          this.formType.mainTable = this.tableData[0].mainTable
          this.formType.mainTableField = this.tableData[0].mainTableField
          this.changeMainTable(this.formType.mainTable)
        }
      }
    },
    saveSubmit(){
      this.$refs.refForm.validate(bol => {
        if(bol){
          this.formType.tableName = this.$props.tableName
          this.formType.tableId = this.$props.tableId
          if(this.formType.id){
            editSurface(this.formType).then(res => {
              if(res.code == 200){
                this.$message.success('编辑成功')
                this.$refs.refDialogForm.closeDialog()
                this.getTableList()
              }
              else{
                this.$message.error(res.msg || '保存失败')
              }
            })
          }
          else{
            addSurface(this.formType).then(res => {
              if(res.code == 200){
                this.$message.success('保存成功')
                this.paging.currentPage = 1
                this.$refs.refDialogForm.closeDialog()
                this.getTableList()
              }
              else{
                this.$message.error(res.msg || '保存失败')
              }
            })
          }
        }
      })
    },
    changeSlaveTable(value){
      if(!value) return this.surfaceSlaveList = []
      this.loadingText = '数据表加载中...'
      this.formLoading = true
      inquireData({tableName:value}).then(res => {
        if(res.code == 200){
          this.formLoading = false
          this.surfaceSlaveList = res.data
        }
        else{
          this.formLoading = false
          this.surfaceSlaveList = []
        }
      }).catch(()=>{
        this.formLoading = false
        this.surfaceSlaveList = []
      })
    },
    changeMainTable(value){
      if(!value) return this.surfaceList = []
      this.loadingText = '数据表加载中...'
      this.formLoading = true
      inquireData({tableName:value}).then(res => {
        if(res.code == 200){
          this.formLoading = false
          this.surfaceList = res.data
        }
        else{
          this.formLoading = false
          this.surfaceList = []
        }
      }).catch(()=>{
        this.formLoading = false
        this.surfaceList = []
      })
    },
    handleSizeChange(val){
      this.paging.pageSize = val
      this.getTableList()
    },
    handleCurrentChange(val){
      this.paging.currentPage = val
      this.getTableList()
    },
    getTableList(){
      const params = {
        size:this.paging.pageSize,
        current:this.paging.currentPage,
        tableName:this.$props.tableName,
        tableId:this.$props.tableId
      }
      getSurfaceList(params).then(res => {
        if(res.code == 200){
          this.tableData = res.data.records
          this.paging.total = res.data.total * 1
        }
        else{
          this.tableData = []
          this.paging.total = 0
        }
      })
    },
    delItem(row){
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delSurface(row.id).then(res => {
          if(res.code == 200){
            this.$message.success('删除成功')
            this.getTableList()
          }
          else{
            this.$message.error(res.msg || '删除失败')
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
